package nmcli

import (
	"bufio"
	"io"
	"io/ioutil"
	"net"
	"os"
	"strconv"
	"strings"
)

func StringIpToInt(ipstring string) int {
	ipSegs := strings.Split(ipstring, ".")
	var ipInt int = 0
	if len(ipSegs) == 4 {
		var ipSeg [4]int
		ipSeg[0], _ = strconv.Atoi(ipSegs[0])
		ipSeg[1], _ = strconv.Atoi(ipSegs[1])
		ipSeg[2], _ = strconv.Atoi(ipSegs[2])
		ipSeg[3], _ = strconv.Atoi(ipSegs[3])
		ipInt, _ = net.IPv4Mask(byte(ipSeg[0]), byte(ipSeg[1]), byte(ipSeg[2]), byte(ipSeg[3])).Size()
	}
	return ipInt
}

// SaveFile saves file at given path
func SaveFile(filepath string, file []byte, permissions int) error {
	return ioutil.WriteFile(filepath, file, os.FileMode(permissions))
}

// GetStdoutText reads out and concats string from io.Reader
func GetStdoutText(r io.Reader) (stdout []string) {
	scanner := bufio.NewScanner(r)
	for scanner.Scan() {
		if lineOut := scanner.Text(); lineOut != "" {
			stdout = append(stdout, lineOut)
		}
	}
	return stdout
}
